package com.chenwy.example.service;

import com.chenwy.example.data.PageInfo;
import com.chenwy.example.entity.main.MiniProgramUser;
import com.chenwy.example.repository.main.MiniProgramUserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2019/5/6.
 */
@Service
public class MiniProgramUserService {

        @Autowired
        private MiniProgramUserRepository miniProgramUserRepository;


        @Transactional
        public void save(MiniProgramUser user){
            miniProgramUserRepository.save(user);
        }

    /**
     * 搜索
     *
     * @param user
     * @param page
     * @return
     */
    public Page<MiniProgramUser> search(MiniProgramUser user, PageInfo page) {
        return miniProgramUserRepository.findAll(new Specification<MiniProgramUser>() {
            @Override
            public Predicate toPredicate(Root<MiniProgramUser> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate nickNameLike = null, genderEqual = null;
                if (user != null) {
                    String nickName = user.getNickName();
                    if (!StringUtils.isEmpty(nickName)) {
                        nickNameLike = criteriaBuilder.like(root.<String>get("nickName"), "%" + user.getNickName() + "%");
                    }

                    String gender = user.getGender();
                    if (!StringUtils.isEmpty(gender)) {
                        genderEqual = criteriaBuilder.equal(root.<String>get("gender"), gender);
                    }
                }
                List<Predicate> list = new ArrayList<Predicate>();
                if (nickNameLike != null) {
                    list.add(nickNameLike);
                }
                if (genderEqual != null) {
                    list.add(genderEqual);
                }
                if (!list.isEmpty())
                    criteriaQuery.where(list.toArray(new Predicate []{}));
                return null;
            }
        },PageRequest.of(page.getPage(),page.getSize(),new Sort(Sort.Direction.DESC,page.getSortName())));
    }

}
